package com.power.service.impl;

import com.power.constant.AuthConstants;
import com.power.factory.LoginStrategyFactory;
import com.power.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 项目自己的认证流程
 * @Author dingchunlin
 * @Date 2024/07/10 21:16
 * @Version 1.0.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //从请求头中获取登录的类型
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
        //根据登录类型，调用不同的认证逻辑
        if (!StringUtils.hasText(loginType)){
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }
        LoginStrategy loginStrategy = loginStrategyFactory.getLoginStrategy(loginType);
        return loginStrategy.realLogin(username);
    }
}
